


#include <iostream>
using namespace std;

// 单例如果在多个线程中都有可能创建，则需要对单例加锁
class SingleMode
{
public:
    static SingleMode *getInstance()
    {
        //先判断是否为空，能提高程序运行效率
        if (instance == NULL)
        {
            unique_lock<mutex> lck(mInstanceMutex);
            if (instance == NULL)
            {
                instance = new SingleMode();
            }
        }
        return instance;
    }
    static void destroy()
    {
        unique_lock<mutex> lck(mInstanceMutex);
        if (instance != NULL)
        {
            delete instance;
            instance = NULL;
        }
    }
    void func() {
        cout << "i am a single instance" << endl;
    }

private:
    SingleMode() {}
    ~SingleMode() {}

    static SingleMode *instance;
    static mutex mInstanceMutex;
};

SingleMode* SingleMode::instance = NULL;
mutex SingleMode::mInstanceMutex;

int main(int argc, char *argv[])
{
    SingleMode::getInstance()->func();
    return 0;
}